package com.zzyl.framework.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Auther: zhaojh
 * @Date: 2025/6/3 - 06 - 03 - 18:05
 * @Description: com.zzyl.framework.interceptor
 * @version: 1.0
 */
@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("authorization");
        if(ObjectUtil.isNull(token)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BaseException("重新登陆");
        }

        try {
            Claims claims = tokenService.parseToken(token);

            Long userId = Long.parseLong(claims.get("userId").toString()) ;
            if(userId==null){
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                throw new BaseException("认证失败");
            }
            UserThreadLocal.set(userId);
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }



        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
